import { SCOPE } from '#constant/index.js';
const env = process.env;
const redirect_uri = encodeURIComponent(
  env.LARK_REDIRECT_URI + '/lark/callBack'
);

const isLarkLogin = async (ctx) => {
  const accessInfo = ctx.session.larkAuth;
  if (!accessInfo) {
    return false;
  }
  const accExpired =
    accessInfo.expires_in + accessInfo.update_time < Date.now();
  const refExpired =
    accessInfo.refresh_expires_in + accessInfo.update_time < Date.now();
  if (accExpired && refExpired) {
    return false;
  }
  if (accExpired && !refExpired) {
    ctx.session.larkAuth && (ctx.session.larkAuth.access_token = '');
    const refreshInfo = await refreshAccessToken(accessInfo.refresh_token, ctx);
    if (!refreshInfo) {
      ctx.session.larkAuth = null;
      return false;
    }
    ctx.session.larkAuth = refreshInfo;
    return true;
  }

  return true;
};

// 获取授权链接
const getLarkAuth = async () => {
  const state = 'random_state_string';
  const scope = SCOPE.join(' ');
  return `${env.LARK_API_HEAD}/authen/v1/index?redirect_uri=${redirect_uri}&app_id=${env.LARK_APP_ID}&state=${state}&scope=${scope}`;
};

// 获取飞书 access_token
const getAccessToken = async (code, ctx) => {
  const response = await ctx.larkHttp.post('/authen/v2/oauth/token', {
    body: {
      grant_type: 'authorization_code',
      code: code,
      redirect_uri: redirect_uri
    }
  });
  if (response.status !== 200) {
    throw new Error(`Failed to get access token: ${response.body}`);
  }
  if (response.data.access_token) {
    return {
      access_token: response.data.access_token,
      refresh_token: response.data.refresh_token,
      expires_in: response.data.expires_in,
      refresh_expires_in: response.data.refresh_token_expires_in,
      update_time: Date.now()
    };
  }
};

const refreshAccessToken = async (refresh_token, ctx) => {
  const response = await ctx.larkHttp.post('/authen/v2/oauth/token', {
    body: {
      grant_type: 'refresh_token',
      refresh_token: refresh_token
    }
  });
  if (response.status !== 200) {
    throw new Error(`Failed to get access token: ${response.body}`);
  }
  // console.log('refres:----------------------------');
  // console.log(data.expires_in, data.access_token);
  if (!response.data.access_token) {
    return false;
  }
  return {
    access_token: response.data.access_token,
    refresh_token: response.data.refresh_token,
    expires_in: response.data.expires_in,
    refresh_token_expires_in: response.data.refresh_token_expires_in,
    update_time: Date.now()
  };
};

export { getLarkAuth, getAccessToken, isLarkLogin };
